package com.lsmw.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsmw.admin.entity.LoginVo;
import com.lsmw.admin.entity.LsAdmin;
import com.lsmw.admin.service.LsAdminService;
import com.lsmw.commonutils.JwtUtils;
import com.lsmw.commonutils.MD5;
import com.lsmw.commonutils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 三号男嘉宾
 * @since 2021-03-23
 */
@CrossOrigin
@Api(tags = "管理员信息")
@RestController
@RequestMapping("/admin/ls-admin")
public class LsAdminController {

    private LsAdminService lsAdminService;
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    public LsAdminController(LsAdminService lsAdminService, RedisTemplate redisTemplate) {
        this.lsAdminService = lsAdminService;
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("login")
    public R login(
            @ApiParam(name = "adminInfo", value = "管理员登录信息")
            @RequestBody LoginVo loginVo) {
        LsAdmin lsAdmin;
        lsAdmin = lsAdminService.getOne(new LambdaQueryWrapper<LsAdmin>()
                .and(qw -> qw.eq(LsAdmin::getAdminName, loginVo.getUsername())
                        .eq(LsAdmin::getAdminPwd, MD5.encrypt(loginVo.getPassword()))));
        if (lsAdmin == null) {
            return R.invalidRequest().data("msg", "账号或密码错误");
        } else {
            String jwtToken = JwtUtils.getJwtToken(
                    String.valueOf(lsAdmin.getAdminId()), lsAdmin.getAdminName(),lsAdmin.getAdminAuth().toString());
            redisTemplate.opsForValue().set(jwtToken, lsAdmin.getAdminId().toString());
            return R.ok().data("token", jwtToken);
        }
    }

    @GetMapping("info")
    public R info(@RequestParam("token") String token) {
        if (token == null || redisTemplate.opsForValue().get(token).isEmpty()) {
            return R.unauthorized().data("msg", "无访问权限");
        }
        Map<String, String> adminInfo;
        try {
            adminInfo = JwtUtils.getUserIdByJwtToken2(token);
        } catch (Exception e) {
            e.printStackTrace();
            return R.unauthorized().data("msg", "无效访问!");
        }
        return R.ok().data("name", adminInfo.get("name"))
                .data("avatar", "https://oflower.oss-cn-beijing.aliyuncs.com/lsmw/img/cf4e1a0c6c86482590d38a5fffbfec4e.GIF")
                .data("roles", lsAdminService.getOne(new LambdaQueryWrapper<LsAdmin>()
                        .eq(LsAdmin::getAdminId, adminInfo.get("id"))).getAdminAuth());
    }

    @PostMapping("logout")
    public R logout(
            @ApiParam(name = "token", value = "token")
            @RequestBody String adminToken) {
        if (adminToken == null){
            return R.invalidRequest().data("msg","请求有误");
        }
        redisTemplate.delete(adminToken.substring(0,adminToken.length()-1));
        return R.ok();
    }

    @ApiOperation(value = "获取所有管理员的信息")
    @GetMapping("/")
    public R getAdmins(HttpServletResponse response) {
        return lsAdminService.getAdmins().setResponseCode(response);
    }

    @ApiOperation("根据id获取管理员信息")
    @GetMapping(value = "/{adminId}")
    public R getAdminById(
            @ApiParam(name = "adminId", value = "管理员id")
            @PathVariable String adminId,
            HttpServletResponse response) {
        return lsAdminService.getAdminById(adminId).setResponseCode(response);
    }

    @ApiOperation("添加管理员")
    @PostMapping("/")
    public R addAdmin(
            @ApiParam(name = "adminInfo", value = "管理员信息")
            @RequestBody LsAdmin lsAdmin,
            HttpServletResponse response) {
        lsAdmin.setAdminPwd(MD5.encrypt(lsAdmin.getAdminPwd()));
        return lsAdminService.addAdmin(lsAdmin) ;
    }

    @ApiOperation(value = "修改管理员信息")
    @PutMapping("/")
    public R updateOrder(
            @ApiParam(name = "lsAdminInfo", value = "管理员信息", required = true)
            @RequestBody LsAdmin lsAdmin,
            HttpServletResponse response) {
        lsAdmin.setAdminPwd(MD5.encrypt(lsAdmin.getAdminPwd()));
        return lsAdminService.updateById(lsAdmin) ? R.ok() : R.invalidRequest();
    }

    @ApiOperation("根据id删除管理员")
    @DeleteMapping("/{adminId}")
    public R deleteAdminById(
            @ApiParam(name = "adminId", value = "管理员id")
            @PathVariable String adminId,
            HttpServletResponse response) {
        return lsAdminService.deleteAdminById(adminId).setResponseCode(response);
    }

    @ApiOperation("根据多个id删除管理员")
    @DeleteMapping("/deleteAdminByIds")
    public R deleteAdminByIds(
            @ApiParam(name = "adminIds", value = "多个管理员id")
            @RequestParam("adminIds") String adminIds,
            HttpServletResponse response) {
        String[] split = adminIds.split(",");
        List<String> list = new ArrayList<>();
        for (String s : split) {
            list.add(s);
        }
        return lsAdminService.deleteAdminByIds(list).setResponseCode(response);
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("/pageAdmin/{current}/{limit}")
    public R getAdminListPage(
            @ApiParam(name = "current", value = "当前页下标", required = true) @PathVariable long current,
            @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable long limit) {
        Page<LsAdmin> adminPage = new Page<>(current, limit);
        lsAdminService.page(adminPage, new LambdaQueryWrapper<LsAdmin>()
                .select(LsAdmin.class, qw -> !qw.getColumn().equals("admin_pwd")));
        Map map = new HashMap();
        map.put("total", adminPage.getTotal());
        map.put("rows", adminPage.getRecords());
        return R.ok().data(map);
    }

    @ApiOperation(value = "根据管理员名查询信息")
    @GetMapping("/admin/{name}/{current}/{limit}")
    public R getAdminInfoById(
            @ApiParam(name = "name", value = "管理员名", required = true) @PathVariable String name,
            @ApiParam(name = "current", value = "当前页下标", required = true) @PathVariable long current,
            @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable long limit) {
        Page<LsAdmin> adminPage = new Page<>(current, limit);
        if (name == null || name == "") {
            lsAdminService.page(adminPage, new LambdaQueryWrapper<LsAdmin>()
                    .select(LsAdmin.class, qw -> !qw.getColumn().equals("admin_pwd")));
        } else {
            lsAdminService.page(adminPage, new LambdaQueryWrapper<LsAdmin>()
                    .like(LsAdmin::getAdminName, name)
                    .select(LsAdmin.class, qw -> !qw.getColumn().equals("admin_pwd")));
        }
        return R.ok().data("rows", adminPage.getRecords()).data("total", adminPage.getTotal());
    }

}

